//
//  HMComposeViewController.swift
//  Weibo
//
//  Created by 李学林 on 15/12/14.
//  Copyright © 2015年 tete. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class HMComposeViewController: UIViewController {
    
    // 记录右toolbar叫出的键盘是否有动画
    var isToolBarAnim: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        // 添加子控件
        // 伪代码
        // 设置UI
        setupUI()
        
    }
    
// 实现设置UI的方法
    private func setupUI(){
        setNavgationView()
        // 添加子控件
        view.addSubview(textView)
        view.addSubview(toolBarView)
        textView.addSubview(composePictureView)
        
        
        // 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        toolBarView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view)
            make.width.equalTo(SCREENW)
            make.height.equalTo(44)
        }
        
        // 因为能滚动,添加到 textView 身上
        // 宽度与高度一样
        // 中心x与 textView 一样
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
            make.top.equalTo(textView).offset(100)
        }

        
        // 设置属性
        toolBarView.childButtonClickClosure = { [weak self] (type: HMComposeToolBarButtonType) -> () in
            switch type {
            case .Picture:
                print("图片")
                self!.selectedPicture()

            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emotion:
                // 切换键盘
                self!.switchKeyboard()
            case .Add:
                print("添加")
            }
        }
        
        // 通知监听键盘弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDidSelected:", name: HMEmoticonButtonDidSelectedNotification, object: nil)
        
    }
    
    
    
    
    // 在方法内部分别设置导航栏的的UI,和底部按钮的UI,和中间的的控件
    private func setNavgationView(){
       // 设置Nav左边的按钮是返回
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Done, target: self, action: "back")
        
        // 设置Nav右边的按钮是自定义视图
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.enabled = false
        //设置中间的titleView
        navigationItem.titleView = titleView
    }
    
    // MARK: - 监听事件
    @objc func emoticonDidSelected(notice: NSNotification){
        
        let emoticon = notice.userInfo!["emoticon"] as! HMEmoticon
        textView.insertEmoticon(emoticon)
    
    }
    
    
    // MARK: - 导航按按钮的处理事件
    @objc private func back(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send(){

        if composePictureView.images.count > 0 {
        
        //发送 "文字+图片" 微博
            upload()
        
        }else{
            
        //发送文字微博
            updata()
        
        }
    }
    
    // 上传图片 + 文字
    private func upload(){
        NetworkTools.shareManager.upload(HMWBUserInfoViewModel.sharedAccount.accessToken!, status: textView.text!, image: composePictureView.images.first!) { (response, error) -> () in
            if error != nil{
                printLog(error)
                SVProgressHUD.showErrorWithStatus("请求失败")
            }else{
            
                SVProgressHUD.showSuccessWithStatus("请求成功")
            
            }
        }
    
    }
    
    // 上传文字信息
    private func updata(){
       

//        // 把 textView 身上的 attributedText 转成表情字符串
//        NetworkTools.shareManager.updata(HMWBUserInfoViewModel.sharedAccount.accessToken!, status: textView.emoticonText) { (response, error) -> () in
//            if error != nil {
//                printLog(error)
//                SVProgressHUD.showErrorWithStatus("发送失败")
//                return

        // 把 textView 身上的 attributedText 转成表情字符串
        
        var result = String()
        
        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (infoDict, range, _) -> Void in
            
            // infoDict : 里面装有当前文字的属性 (字体大小,风格)
            // range    : 代表当前遍历到的文字或者文字附件的范围
            // *stop    : 给其赋值值,让遍历停止
            printLog(infoDict)
            if let attachment = infoDict["NSAttachment"] as? HMTextAttachment {
                printLog(attachment.emoticon?.chs)
                // 取到 attachment 身上对应图片对应的表情字符串
                result += attachment.emoticon!.chs!
            }else {
                // 通过 range 取到对应的文字
                result += (self.textView.attributedText.string as NSString).substringWithRange(range)
            }
            
        }
    }
    /// 键盘的 frame 高度改变的通知
    ///
    /// - parameter noti: 通知
    @objc private func keyboardWillChangeFrame(noti: NSNotification){
        printLog(noti)
        // 如果  isToolBarAnim 为 true 才执行动画
        if !isToolBarAnim {
            return
        }

        
        
        // 取到键盘的结束位置
        let endRect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 取到动画执行时间
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        // 把 toolBar 的底部改成 endRect 里面y 里面
        toolBarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(endRect.origin.y - self.view.height)
        }
        
        UIView.animateWithDuration(duration.doubleValue) { () -> Void in
            self.toolBarView.layoutIfNeeded()
        }
    }
    

    
    // MARK: - 懒加载控件
    // NavgationItem右侧的按钮
    private lazy var sendButton: UIButton = {
    
        let button = UIButton()
        
        button.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        // 设置背景图片(普通状态)common_button_orange_highlighted
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        // 设置背景图片(高亮状态)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        // 设置背景图盘(禁用状态)common_button_white_disable
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        // 设置不同状态下得字体颜色
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        // 设置文字15(发送)和大小45  30
        button.setTitle("发送", forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.size = CGSize(width: 45, height: 30)
        return button
    
    }()
    //NavgationItem的titleView
    private lazy var titleView: UILabel = {
    
        let titleView = UILabel()
        
//*******************************************************************************
        // 用Label 的富文本属性 设置titleView的相关属性
        if let name = HMWBUserInfoViewModel.sharedAccount.userAccount?.screen_name {
            // 设置多行显示
            titleView.numberOfLines = 0
            // 通过内容生成一个富文本对象
            let attrText = NSMutableAttributedString(string: "发微博\n\(name)")
            let range = (attrText.string as NSString).rangeOfString(name)
            
            //            let attrss = [
            //                NSStrokeWidthAttributeName: 2,
            //                NSStrokeColorAttributeName: UIColor.greenColor()
            //            ]
            //            attrText.addAttributes(attrss, range: NSMakeRange(0, 3))
            
            // 设置对应位置的字体属性
            let attrs = [
                NSFontAttributeName: UIFont.systemFontOfSize(14),
                NSForegroundColorAttributeName: UIColor.grayColor()
            ]
            attrText.addAttributes(attrs, range: range)
            
            // 设置到 label上去
            titleView.attributedText = attrText
        }else {
            titleView.text = "发微博"
        }
        // 设置文字居中
        titleView.textAlignment = .Center
        // 适配内容大小
        titleView.sizeToFit()
        // NSMutableAttributedString
//*************************************************************************************
        return titleView
    }()
    
    /// 懒加载
    // 懒加载中间的textView
    private lazy var textView: HMComposeTextView = {
        let textView = HMComposeTextView()
        // 设置字体16
        textView.font = UIFont.systemFontOfSize(16)
        
        // 设置展位文字(需要在IBInspect...中添加UITextView的placeholder属性)
        textView.placeholder = "给你空间写心情哟~"
        // 设置代理监听textView的文本变化
        textView.delegate = self
        
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    
    // 懒加载底部的toolBar控件
    private lazy var toolBarView: HMComposeToolBarView = HMComposeToolBarView(frame:CGRectZero)
    
    // 懒加载表情键盘视图
    private lazy var emoticonKeyboard: HMComposeEmotionKeybord = {
        let emotionView = HMComposeEmotionKeybord()
//        emotionView.backgroundColor = UIColor.redColor()
        emotionView.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        
        return emotionView
    }()
    
    //懒加载中间添加图片的控件
    private lazy var composePictureView: HMComposePictureView = {
    
        let pictureView = HMComposePictureView()
        // 添加图片要调用的闭包
        pictureView.addImageClosure = { [weak self] in
            self?.selectedPicture()
        }
        pictureView.backgroundColor = self.textView.backgroundColor
        
        return pictureView
    
    }()

}


// MARK: - 处理toolBar 按钮点击
extension HMComposeViewController {
    // 选择图片
    private func selectedPicture(){
        // 弹出选择照片的控制器
        let pickerVC = UIImagePickerController()
        // 判断照相机是否可用
        // let result = UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary)
        //        // 判断照相机前后摄像头是否可用
        //        UIImagePickerController.isCameraDeviceAvailable(.Rear)
        // 是否允许编辑图片,默认不开启
        // pickerVC.allowsEditing = true
        pickerVC.delegate = self
        presentViewController(pickerVC, animated: true, completion: nil)
    }
    
    
    // 切换表情键盘
    private func switchKeyboard(){
        
        // 实现点击切换键盘的功能
        isToolBarAnim = false
        
        // 1. 让textView退出第一响应者
        textView.resignFirstResponder()
        // 2.切换键盘------关键点---系统键盘textView.inputView是nil(作为判断的关键)
        if textView.inputView == nil {
            textView.inputView = emoticonKeyboard
        }else{
            textView.inputView = nil
        }
        
        isToolBarAnim = true
        
        // 用于告诉toolBarView按钮图片该显示哪一个?
        toolBarView.isEmoticonKeyboard = (textView.inputView != nil)
        
        // 3. 弹出键盘成为第一响应者
        textView.becomeFirstResponder()
        
    }
    
}

// MARK: - 选择图片控制器的代理方法
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        
        
        // 注意:scaleToWidth方法是为了防止图片过大,造成内存暴涨!!!!!!!!!这是重点
        composePictureView.addImage(image.scaleToWidth(600))
        // 关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        printLog("点击取消了")
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}


// MARK: - UITextViewDelegate代理方法
extension HMComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}

